﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using devtm.Configuration;

namespace devtm.Editor.Configuration.Command
{



    /// <summary>
    /// Implemente le pattern Command
    /// </summary>
    public class CommandManager : INotifyPropertyChanged
    {


        internal static bool InUndo = false;

        public CommandManager()
        {
            ListeUndo = new Stack<ICommand>();
            ListeRedo = new Stack<ICommand>();
        }


        public void Do(ICommand command)
        {

            if (CommandManager.InUndo)
                return;

            ListeUndo.Push(command);
            ListeRedo.Clear();

            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("CanUndo"));
                PropertyChanged(this, new PropertyChangedEventArgs("CanRedo"));
            }

            Datas.TestChange();

        }


        public void Clear()
        {

            ListeUndo.Clear();
            PropertyChanged(this, new PropertyChangedEventArgs("CanUndo"));

            ListeRedo.Clear();
            PropertyChanged(this, new PropertyChangedEventArgs("CanRedo"));

        }


        public Stack<ICommand> ListeUndo { get; private set; }
        public Stack<ICommand> ListeRedo { get; private set; }

        public event PropertyChangedEventHandler PropertyChanged;

        public bool CanRedo
        {
            get
            {
                return ListeRedo.Count != 0;
            }
        }

        public bool CanUndo
        {
            get
            {
                return ListeUndo.Count != 0;
            }
        }


        public void Undo()
        {

            CommandManager.InUndo = true;

            ICommand c = ListeUndo.Pop();
            c.Undo();
            ListeRedo.Push(c);
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("CanUndo"));
                PropertyChanged(this, new PropertyChangedEventArgs("CanRedo"));
            }

            CommandManager.InUndo = false;

        }

        internal void Redo()
        {

            CommandManager.InUndo = true;

            ICommand c = ListeRedo.Pop();
            c.Redo();
            ListeUndo.Push(c);
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("CanRedo"));
                PropertyChanged(this, new PropertyChangedEventArgs("CanUndo"));
            }

            CommandManager.InUndo = false;
        }



    }


}
